const express = require('express')
const socket = require('socket.io')
const app = express()
const http = require('http').createServer(app)
const path = require('path')
const io = socket(http, {
    cors:true
})
app.use(express.static(path.join(__dirname,'public')))


let userList = []
let messageList = []
io.on('connection', socket => {
    console.log('有新用户连接');
    console.log(socket.id);
    socket.on('login', obj => {
        if (!userList.some(item=>socket.id === item.sid)) {
            userList.push({user: obj.user ,sid :socket.id })
        }
        socket.emit('login', {user: obj.user ,sid :socket.id })
        socket.emit('newUser', {user: obj.user ,sid :socket.id })
        socket.broadcast.emit('newUser', {user: obj.user ,sid :socket.id })
        socket.emit('refreshUserList', userList)
        socket.broadcast.emit('refreshUserList', userList)
    })
    socket.on('message', obj => {
        messageList.push({ user: obj.user, sid: socket.id, message: obj.message })
        socket.emit('message',{ user: obj.user, sid: socket.id, message: obj.message })
        socket.broadcast.emit('message',{ user: obj.user, sid: socket.id, message: obj.message })
    })
    socket.on('disconnect', obj => {
        console.log('用户断开连接');
        let index = userList.findIndex(item=>item.sid === socket.id)
        if (index > -1) {
            socket.broadcast.emit('leaveUser', userList[index])
            userList.splice(index, 1)
            socket.emit('refreshUserList', userList)
            socket.broadcast.emit('refreshUserList', userList)
        }
    })
})

http.listen(3000, () => {
    console.log('服务器已启动');
})